//
//  MainController.m
//  吃货·上海
//
//  Created by 濮亚军 on 15/11/24.
//  Copyright © 2015年 濮亚军. All rights reserved.
//

#import "MainController.h"
#import "MineController.h"
#import "SHMenuRootViewController.h"
#import "DessertCollectionViewController.h"
#import "SHMenuFindViewController.h"
#import "CommunityController.h"
#import "IssueController.h"
#import <BmobSDK/BmobProFile.h>
#import <BmobSDK/Bmob.h>
#import "RegistViewController.h"  // 跳转注册界面

#import "UIImageView+WebCache.h"


#import "CommunityCell.h"
#import "UserShareModel.h"
#import "KFBannerView.h"

@interface MainController ()<UINavigationControllerDelegate,UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate>
//社区子控制器
@property(nonatomic, strong)CommunityController *communityViewVc;

//点心子控制器
@property(nonatomic, strong)DessertCollectionViewController *dessertViewVc;

//我的子控制器
@property(nonatomic, strong)MineController *mineViewVc;

//发布界面
@property(nonatomic, strong)IssueController *issueViewVc;

//左barButton
@property(nonatomic, strong)UIButton *leftButton;

//右BarButton
@property(nonatomic, strong)UIButton *rightButton;



@property (nonatomic,strong)UITableView *tableView;

@property (nonatomic,strong)NSMutableArray *array;
@property (nonatomic,strong)NSMutableArray *modelArray;

@property (strong, nonatomic) KFBannerView *bannerView;

@end

@implementation MainController
{
    NSInteger curPage;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    

    [self getValue];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight - 64) style:UITableViewStylePlain];
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    
    
    
    /**
     *  注册表头 cell
     */
//    [self.tableView registerClass:[MainHeaderView class] forHeaderFooterViewReuseIdentifier:@"header"];
    
    [self.tableView registerClass:[CommunityCell class] forCellReuseIdentifier:@"cell"];
    
    
    
    self.navigationController.navigationBar.barTintColor = kBarColor;
    self.navigationController.navigationBar.translucent = NO;
    //rself.view.backgroundColor = KMyColor;
    self.navigationItem.title = @"首页";
    
    //自定义底部按钮
    self.mainBottomView = [[MainBottomView alloc]initWithFrame:CGRectMake(0, KScreenHeight - 64 - 64, KScreenWidth, 64)];
    self.mainBottomView.backgroundColor = kBarColor;
    //NSLog(@"self.mainBottom === %@", self.mainBottomView);
    [self.view addSubview:_mainBottomView];
    
    
    //UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc]initWithTitle:@"菜单" style:UIBarButtonItemStylePlain target:self action:@selector(leftButton:)];
    //self.navigationItem.leftBarButtonItem = leftBarButton;
    
//    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc]initWithTitle:@"我的" style:UIBarButtonItemStylePlain target:self action:@selector(rightButton:)];
//    self.navigationItem.rightBarButtonItem = rightBarButton;
    
    //添加社区子controller
    self.communityViewVc = [[CommunityController alloc]init];
    self.communityViewVc.view.hidden = YES;
    [self addChildViewController:_communityViewVc];
    [self.view addSubview:_communityViewVc.view];
    
    //点心子controller
    self.dessertViewVc = [[DessertCollectionViewController alloc]init];
    self.dessertViewVc.view.hidden = YES;
    [self addChildViewController:_dessertViewVc];
    [self.view addSubview:_dessertViewVc.view];
    
    //添加我的子controller
    self.mineViewVc = [[MineController alloc]init];
    self.mineViewVc.view.hidden = YES;
    [self addChildViewController:_mineViewVc];
    [self.view addSubview:_mineViewVc.view];
    
    //前往我的发布
    UITapGestureRecognizer *submitTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(submitTap:)];
    [self.mineViewVc.userView.minePushView addGestureRecognizer:submitTap];
    
    //添加发布子控制器
    self.issueViewVc = [[IssueController alloc]init];
    self.issueViewVc.view.hidden = YES;
    NSLog(@"self.issueViewVc === %@", self.issueViewVc);
    [self addChildViewController:_issueViewVc];
    [self.view addSubview:_issueViewVc.view];
    
    //菜谱添加手势
    UITapGestureRecognizer *shMenuTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(shMenuTapAction:)];
    [self.mainBottomView.menuButtonView addGestureRecognizer:shMenuTap];
    
    //社区添加手势
    UITapGestureRecognizer *communityTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(communityTapAction:)];
    [self.mainBottomView.communityButtonView addGestureRecognizer:communityTap];
    
    //点心手势
    UITapGestureRecognizer *dessertTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dessertTapAction:)];
    [self.mainBottomView.dailyButtonView addGestureRecognizer:dessertTap];
    
    //我的手势
    UITapGestureRecognizer *mineTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(mineTapAction:)];
    [self.mainBottomView.mineButtonView addGestureRecognizer:mineTap];
    
    //发布手势
    UITapGestureRecognizer *issueTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(issueTapAction:)];
    [self.mainBottomView.cameraButtonView addGestureRecognizer:issueTap];
    
    //左BarButton
    self.leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.leftButton.frame = CGRectMake(0, 0, 25, 25);
    //[self.leftButton setImage:[[UIImage imageNamed:@""] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [self.leftButton setImage:[[UIImage imageNamed:@"homePG"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateSelected];
    [self.leftButton addTarget:self action:@selector(leftButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc]initWithCustomView:_leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    
    //NSLog(@"self.navigationController === %@",self.navigationController);
    
    //右BarButton
    self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.rightButton.frame = CGRectMake(0, 0, 25, 25);
    [self.rightButton setImage:[[UIImage imageNamed:@"photo"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateSelected];
    [self.rightButton addTarget:self action:@selector(rightButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    NSLog(@"rightButton ===== %@",self.rightButton);
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc]initWithCustomView:_rightButton];
    self.navigationItem.rightBarButtonItem = rightBarButton;
    
    
}


- (void)getValue
{
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"Menu"];
    //查找GameScore表的数据
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        NSLog(@"%@",array);
        self.array = [NSMutableArray array];
        for (BmobObject *obj in array) {
            //打印playerName
            NSLog(@"obj.playerName = %@", [obj objectForKey:@"playerName"]);
            BmobFile *file = [obj objectForKey:@"icon"];
            if (self.array.count < 3) {
                [self.array addObject:file.url];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
        });
    }];
    
    BmobQuery *query = [BmobQuery queryWithClassName:@"UserPush"];
    [query orderByDescending:@"createdAt"];
    //查找GameScore表的数据
    [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        NSLog(@"%@",array);
        self.modelArray = [NSMutableArray array];
        for (BmobObject *obj in array) {
            UserShareModel *model = [[UserShareModel alloc]initWithbmobObject:obj];
            if (self.modelArray.count < 5) {
                [self.modelArray addObject:model];
            }
            // 数组排序
//            [self.modelArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
//                
//            }];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    }];
    
}

// tableView 方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.modelArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.modelArray.count == 0)
    {
        return 0;
    }
    else
    {
        UserShareModel *model = self.modelArray[indexPath.row];
        return [CommunityCell heightForCell:model];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat sectionHeaderHeight = 200;
    
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        
    }
    
}
 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommunityCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (self.modelArray.count != 0)
    {
        [cell setUserShareModel:self.modelArray[indexPath.row]];
    }
    return cell;
}

// tableView表头
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 200;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 0; i < 4; i++)
    {
        NSString *string = [NSString stringWithFormat:@"%d.jpg",i];
        [array addObject:string];
    }
    
    self.bannerView = [[KFBannerView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 200)];
    self.bannerView.imageArray = array;
    [self.view addSubview:_bannerView];
    
    UITapGestureRecognizer *tapHeader = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(shMenuTapAction:)];
    [self.bannerView addGestureRecognizer:tapHeader];
    return self.bannerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.navigationItem.title = @"吃货圈";
    self.communityViewVc.view.hidden = NO;
    self.mineViewVc.view.hidden = YES;
    self.dessertViewVc.view.hidden = YES;
    self.issueViewVc.view.hidden = YES;
    self.leftButton.selected = YES;
    self.rightButton.selected = NO;
    
}

//跳转菜谱
-(void)shMenuTapAction:(UITapGestureRecognizer *)shMenuTap
{
    SHMenuFindViewController *SHMenuViewVc = [[SHMenuFindViewController alloc]init];
    [self.navigationController pushViewController:SHMenuViewVc animated:NO];
}
//跳转社区
-(void)communityTapAction:(UITapGestureRecognizer *)communityTap
{
    //NSLog(@"社区");
    self.navigationItem.title = @"吃货圈";
    self.communityViewVc.view.hidden = NO;
    self.mineViewVc.view.hidden = YES;
    self.dessertViewVc.view.hidden = YES;
    self.issueViewVc.view.hidden = YES;
    self.leftButton.selected = YES;
    self.rightButton.selected = NO;
}
//跳转我的
-(void)mineTapAction:(UITapGestureRecognizer *)mineTap
{
    self.navigationItem.title = @"我是吃货";
    self.communityViewVc.view.hidden = YES;
    self.mineViewVc.view.hidden = NO;
    self.mineViewVc.loginView.hidden = YES;
    self.mineViewVc.userView.hidden = NO;
    self.mineViewVc.forgetPWView.hidden = YES;
    self.dessertViewVc.view.hidden = YES;
    self.issueViewVc.view.hidden = YES;
    self.leftButton.selected = YES;
    self.rightButton.selected = NO;
}
//发布
-(void)submitTap:(UITapGestureRecognizer *)submitTap
{
    self.navigationItem.title = @"晒吃货";
    self.communityViewVc.view.hidden = YES;
    self.mineViewVc.view.hidden = YES;
    self.dessertViewVc.view.hidden = YES;
    self.issueViewVc.view.hidden = NO;
    self.leftButton.selected = YES;
    self.rightButton.selected = YES;
}
//跳转到点心
-(void)dessertTapAction:(UITapGestureRecognizer *)dessertTap
{
    self.navigationItem.title = @"心爱点心";
    self.communityViewVc.view.hidden = YES;
    self.mineViewVc.view.hidden = YES;
    self.dessertViewVc.view.hidden = NO;
    self.issueViewVc.view.hidden = YES;
    self.leftButton.selected = YES;
    self.rightButton.selected = NO;
}

//跳转到发布
-(void)issueTapAction:(UITapGestureRecognizer *)issueTap
{
    self.navigationItem.title = @"晒吃货";
    self.communityViewVc.view.hidden = YES;
    self.mineViewVc.view.hidden = YES;
    self.dessertViewVc.view.hidden = YES;
    self.issueViewVc.view.hidden = NO;
    self.leftButton.selected = YES;
    self.rightButton.selected = YES;
}
//左边BarButton点击事件 返回主页
-(void)leftButtonAction:(UIButton *)leftButton
{
    self.navigationItem.title = @"我的";
    self.communityViewVc.view.hidden = YES;
    self.mineViewVc.view.hidden = YES;
    self.dessertViewVc.view.hidden = YES;
    self.issueViewVc.view.hidden = YES;
    self.leftButton.selected = YES;
    self.rightButton.selected = NO;
}
//右边BarButton点击事件
-(void)rightButtonAction:(UIButton *)rightButton
{
    if (self.rightButton.selected == YES)
    {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            NSLog(@"打开摄像头成功");
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            picker.allowsEditing = YES;
            picker.delegate = self;
            [self presentViewController:picker animated:YES completion:nil];
        }
        else{
            UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"打开摄像头失败" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alterView show];
            
            NSLog(@"打开摄像头失败");
        }
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    NSLog(@"ok");
    //  1.将选中的图片赋值给imageView
    //  通过字典的key值来取出对应的value值，value就是选中的图片
    UIImage *image= [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        //  将某一张图片存到相册中
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    }
    //给上传图片区域附上图片
    self.issueViewVc.issueView.issueImageView.image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    //获取时间来命名图片
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    self.issueViewVc.nowTime = [NSString stringWithFormat:@"%f", a];
    NSLog(@"nowTime ==== %@", self.issueViewVc.nowTime);
    [self saveImage:image WithName:[self.issueViewVc.nowTime stringByAppendingString:@".jpg"]];
    
    //  2.将本界面模态回去，即dismiss
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
{
    NSData* imageData = UIImagePNGRepresentation(tempImage);
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    // Now we get the full path to the file
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    // and then we write it out
    [imageData writeToFile:fullPathToFile atomically:NO];
}
/*
-(void)leftButton:(UIBarButtonItem *)barButton
{
    SHMenuRootViewController *SHMenuViewVc = [[SHMenuRootViewController alloc]init];
    [self.navigationController pushViewController:SHMenuViewVc animated:NO];
}
*/

// 测试跳转
/*
-(void)rightButton:(UIBarButtonItem *)barButton
{
 
    RegistViewController *registVc = [[RegistViewController alloc]init];
    [self.navigationController pushViewController:registVc animated:NO];
 
}
*/

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
